import axios from 'axios';
const configUrl = require('@/utils/configUrl');

const domain = configUrl.LINK.domain;

let time = 0;
let timeHandler = null;
function requestTime() {
  return axios.get(`${process.env.VUE_APP_BASE_API}${domain}user/getTime`).then(({ data }) => {
    if (data.isSuccess && data.content && data.content.time) {
      return Promise.resolve(data.content.time);
    } else {
      return Promise.resolve(new Date().getTime());
    }
  });
}

// 开始请求时间定时器
function startLoop() {
  timeHandler && clearTimeout(timeHandler);
  timeHandler = setTimeout(() => {
    requestTime().then((t) => {
      time = t;
    });
    startLoop();
  }, 1000 * 60 * 30);
}

let loading = false;
let pendingList = [];
export function getServerTime() {
  if (time) return Promise.resolve(time);
  startLoop();

  if (loading) {
    return new Promise((resolve, reject) => {
      pendingList.push((t) => {
        resolve(t);
      });
    });
  } else {
    loading = true;
    return requestTime().then((t) => {
      loading = false;
      time = t;
      
      if (pendingList.length) {
        pendingList.forEach((fn) => fn(t));
        pendingList.length = 0;
      }
      return Promise.resolve(time);
    });
  }
}

export function resetTime() {
  time = 0;
}
